<template>
	<view class="container column-start-flex">
		
		
		<view class="" >
			<view class="head">
				<view class="head-title_1">
					<text v-if="pageType == 'password'">{{$t('login.mimadenglu')}}</text>
					<text v-else-if="pageType == 'retrieve'">{{$t('zhaohui_mima')}}</text>
					<text v-else>{{$t('mobile_zhuce')}}</text>
				</view>
				<view v-if="pageType == 'phone'" class="head-title_2"></view>
			</view>
			<view class="body">
				<u--form labelPosition="left" :model="loginModel" :rules="rules" ref="form">
					<u-form-item prop="email" borderBottom>
						<view class="form-item main-start-flex">
							<u--image src="/static/my/email.png" width="34rpx" height="34rpx">
							</u--image>
							<u--input v-model="loginModel.email" border="none" :placeholder="$t('login.email')"></u--input>
						</view>
					</u-form-item>
					<u-form-item prop="code" borderBottom v-if="pageType != 'password'">
						<view class="form-item main-start-flex">
							<u--image src="/static/my/code.png" width="34rpx" height="34rpx">
							</u--image>
							<u--input v-model="loginModel.code" border="none" :placeholder="$t('put_ma')"></u--input>
							<view class="get-code main-center-flex">
								<text v-if="!isGetCode" @click="getCode">{{$t('yamzhemgma')}}</text>
								<text v-else>{{codeTime}}s</text>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="password" borderBottom >
						<view class="form-item main-start-flex">
							<u--image src="/static/my/password.png" width="34rpx"
								height="34rpx">
							</u--image>
							<u--input v-model="loginModel.password" border="none" :placeholder="$t('login.password')"
								:password="pwd_put"></u--input>
							<view class="get-code main-center-flex">
								<image v-if="show_pwd == true" @click="showPwd('close')" src="/static/my/yanjing.png" style="width: 50rpx;" mode="widthFix"></image>
								<image v-if="show_pwd == false" @click="showPwd('open')"  src="/static/my/guanbiyanjing.png" style="width: 50rpx;" mode="widthFix"></image>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="checked" borderBottom v-if="pageType == 'phone'">
						<view class="form-item main-start-flex" >
							<image v-if="loginModel.checked == false" src="/static/my/kegouxuan.png" style="width: 40rpx;margin-right: 20rpx;" mode="widthFix"></image>
							<image v-if="loginModel.checked == true" src="/static/my/gouxuan.png" style="width: 40rpx;margin-right: 20rpx;" mode="widthFix"></image>
							<view class="agreement">
								{{$t('Read And Agree')}}<text @click="openBox(1)">《{{service_title}}》</text>、<text @click="openBox(2)">《{{public_title}}》</text>
							</view>
						</view>
					</u-form-item>
				</u--form>
			</view>
			<view class="login-button main-center-flex" >
				<view v-if="pageType == 'password'" @click="login()" >{{$t('dologin')}}</view>
				<view v-else-if="pageType == 'retrieve'" @click="changePwd()">{{$t('Submit')}}</view>
				<view v-else @click="registUser()">{{$t('liji_zhuce')}}</view>
			</view>
			<view class="password-login">
				<view @click="changeLoginPage('password')" v-if="pageType == 'phone'">
					{{$t('with_pwd')}}
				</view>
								
				<view class="main-center-flex" style="position: relative;" v-if="pageType == 'password'">
					<view class="" @click="questLogin">{{$t('login.zhuce')}}</view>
					<view class="line"></view>
					<view class="" style="margin-left: 80rpx;" @click="changeLoginPage('retrieve')">{{$t('login.wangji')}}</view>
				</view>
					
				<view class="main-center-flex" style="position: relative;" v-if="pageType == 'retrieve'">
					<view class="" @click="questLogin">{{$t('kuaijie_zhuce')}}</view>
					<view class="line"></view>
					<view class="" style="margin-left: 80rpx;" @click="changeLoginPage('password')">{{$t('mima_denglu')}}</view>
				</view>
			</view>
			
		</view>
	
	
		<u-popup :show="showBox" :round="10" mode="bottom" @close="closeBox" >
			<view style="height: 10rpx;"></view>
			<scroll-view class="scrollable-area" scroll-y="true" >
				<rich-text :nodes="show_content" style="line-height: 60rpx;text-align: left;"></rich-text>
				
				<view class="agren_btn" @click="hasRead">
					<view style="width: 60rpx;">
						<image src="/static/my/xuanzhong.png" class="xuanzhong"></image>
					</view>		
					
					 <view class="" style="display: flex;justify-content: center;align-items: center;">
					 	{{$t('has_read')}}
					 </view>			
				</view>
				<view style="height: 26rpx;">
					
				</view>		
			</scroll-view>
			
			<view style="height: 56rpx;"></view>
		</u-popup>
	</view>
</template>

<script>
import baseUrl from '@/utils/siteInfo.js';
	import {
		mapGetters,
		mapState
	} from 'vuex';
	import {
		get_login_emscode,
		login_by_sms,
		login_by_account,
		login_forget,
		mini_wx_login,
		getPhone
	} from '@/api/login.js';
	import {
		getArticleDetail
	} from '@/api/article.js';
	export default {
		data() {
			return {
				logo_url: baseUrl.imgroot + '/static/picture/logo.jpeg',
                miniapp_logo_pic: '../../../static/logo.png',
				user_relation: '',
				show_pwd:false,
				pwd_put:true,
				weixin_other_login: false,
				checked: false,
				// #ifdef  MP-WEIXIN
				weixin: true,
				// #endif
				// #ifdef APP-PLUS || H5
				weixin: false,
				// #endif
				pageType: 'phone',
				loginModel: {
					email: '',
					code: '',
					checked: false,
					password: ''
				},
				register:'register',//resetpwd  register  changemobile  changepwd
				rules: {
					email: [{
							type: 'string',
							required: true,
							message: this.$t('login.email'),
							trigger: ['blur', 'change']
						},
						{
							// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return uni.$u.test.email(value);
							},
							message: this.$t('login.zhengque'),
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ["change", "blur"],
						}
					],
					code: [{
							type: 'number',
							required: true,
							message: this.$t('put_ma'),
							trigger: ['blur', 'change']
						},
						{
							// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return uni.$u.test.code(value, 4);
							},
							message: this.$t('put_zhenquema'),
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ["change", "blur"],
						}
					],
					password: {
						type: 'string',
						required: true,
						message: this.$t('login.password'),
						trigger: ['blur', 'change']
					}
				},
				isGetCode: false,
				codeTime: 60,
				codeInterval: null,
				service_title:'',
				service_content:'',
				public_title:'',
				public_content:'',
				show_title:'',
				show_content:'',
				showBox:false,
				read_type:1,
				read_service_finish:false,
				read_public_finish:false,
			}
		},
		computed: {
			...mapGetters('phone', {
				phoneHieght: 'phoneHieght',
			}),
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(parms) {
			this.pageType = parms.type;
			if(this.pageType == 'phone'){
				this.event = 'register';
			}
			if(this.pageType == 'retrieve'){
				this.event = 'resetpwd';
			}
		},
		onShow() {
			let miniapp_logo_pic = uni.getStorageSync('_miniapp_logo_pic')
			if (miniapp_logo_pic) {
			    this.miniapp_logo_pic = miniapp_logo_pic;
			}
			let miniapp_user_relation = uni.getStorageSync('_miniapp_user_relation');
			if (miniapp_user_relation) {
			    this.user_relation = miniapp_user_relation;
			}
			this.getArticleDetailFunc()
		},
		methods: {
			gotopage(url){
				uni.switchTab({
					url:url
				})
			},
			goToRule(val) {
				if (val == 0) {
					uni.navigateTo({
						url: '/pages/my/xieyi/user'
					})
				} else {
					uni.navigateTo({
						url:  '/pages/my/xieyi/yinsi'
					})
				}
			},
			clickInfo() {
				uni.$u.toast(this.$t('please_read'))
			},
			checkedChange(item) {
				this.checked = !this.checked
			},
			decryptPhoneNumber(e) {
                //手机号授权登录https://zhuanlan.zhihu.com/p/420751667
				if(!e.detail.code){
                    uni.showToast({
                        icon: 'none',
                        title: e.detail.errMsg
                    });
					return ''
				}
				const storageKey = '_USER_ACCESS_TOKEN';
				const self = this;
				uni.login({
					scopes: 'auth_base',
					success(result) {
						console.log(e)
						console.log(result)
						if (result.errMsg === 'login:ok') {
							self.code = result.code;
							mini_wx_login({
								code: result.code,
								phone_code: e.detail.code,
								user_relation: self.user_relation
							}).then(response => {
								if (response.code === 0) {
									uni.setStorageSync('_USER_ACCESS_TOKEN', response.data.token);
									self.$store.dispatch('user/USER_CONFIG')
									uni.switchTab({
										url: '/pages/index/index'
									})
									uni.showToast({
										icon: 'none',
										title: '登录成功'
									})


								} else {
									uni.showToast({
										icon: 'none',
										title: response.msg
									})

								}
							})
						}
					}
				})
			},
			back() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			login() {
				var self= this;
				uni.showLoading();
				this.$refs.form.validate().then(res => {
					let {
						email,
						code,
						password,
					} = this.loginModel
					
					login_by_account({
						email,
						code,
						password,
					}).then(res => {
						if (res.code == 0) {
							uni.setStorageSync('_USER_ACCESS_TOKEN', res.data.token);
							self.$store.dispatch('user/USER_CONFIG')
							uni.switchTab({
								url: '/pages/index/index'
							})
						}else{
							uni.$u.toast(res.msg)
						}
						uni.hideLoading();
					}).catch(err => {
						uni.$u.toast(err.msg);
						uni.hideLoading();
					})
				}).catch(errors => {
					uni.hideLoading();
				})
			},
			registUser(){
				if(this.read_service_finish == false){
					uni.$u.toast(this.$t('please_read'));
					return '';
				}
				if(this.read_public_finish == false){
					uni.$u.toast(this.$t('please_read2'));
					return '';
				}
				var self= this;
				uni.showLoading();
				this.$refs.form.validate().then(res => {
					console.log(self.loginModel);
					let params = {};
					params.username = self.loginModel.email;
					params.email = self.loginModel.email;
					params.code = self.loginModel.code;
					params.password = self.loginModel.password;
				
					login_by_sms(params).then(res => {
						if (res.code == 0) {
							//走 H5登錄
							self.login();
						}else{
							uni.$u.toast(res.msg)
						}
						uni.hideLoading();
					}).catch(err => {
						uni.$u.toast(err.msg);
						uni.hideLoading();
					})
				}).catch(errors => {
					console.log('ee',errors);
					uni.hideLoading();
				})
			},
			changePwd(){
				var self= this;
				uni.showLoading();
				this.$refs.form.validate().then(res => {
					console.log(self.loginModel);
					let params = {};
					params.email = self.loginModel.email;
					params.captcha = self.loginModel.code;
					params.newpassword = self.loginModel.password;
				
					login_forget(params).then(res => {
						if (res.code == 0) {
							//走 H5登錄
							self.login();
						}else{
							uni.$u.toast(res.msg)
						}
						uni.hideLoading();
					}).catch(err => {
						uni.$u.toast(err.msg);
						uni.hideLoading();
					})
				}).catch(errors => {
					console.log('ee',errors);
					uni.hideLoading();
				})
			},
			changeLoginPage(type) { 
				
				this.loginModel = {
					email: '',
					code: '',
					checked: true,
					password: ''
				}
				if(type == 'retrieve'){
					this.event = 'resetpwd';//頑疾密碼
				}
				if(type == 'phone'){
					this.event = 'register';//頑疾密碼
				}
				uni.navigateTo({
					url: '/pages/my/login/index?type=' + type
				})
			},
			questLogin() {
				uni.navigateTo({
					url: '/pages/my/login/index?type=phone'
				})
			},
			getCode() {
				console.log('发送验证码')
				clearInterval(this.codeInterval)
				var res = this.$refs.form.validateField('email');
				if(this.loginModel.email == ''){
					return '';
				}
				var params = {
					email: this.loginModel.email,
					event: this.event
				};
				console.log(params);
				uni.showLoading();
				get_login_emscode(params).then(res => {
					console.log('发送验证码', res)
					uni.hideLoading();
					uni.$u.toast(res.msg)
					if (res.code == 0) {
						this.isGetCode = true
						this.codeInterval = setInterval(() => {
							if (this.codeTime > 0) {
								this.codeTime--
							} else {
								clearInterval(this.codeInterval)
								this.isGetCode = false
							}
						}, 1000)
					}
				}).catch(err => {
					uni.hideLoading();
					uni.$u.toast(err.msg)
				})

			},
			getArticleDetailFunc(){
				getArticleDetail({id:2}).then(res=>{
					if(res.code == 0){
						this.service_title = res.data.title;
						this.service_content = this.imgDesc(res.data.descript);
					}
				});
				getArticleDetail({id:3}).then(res=>{
					if(res.code == 0){
						this.public_title = res.data.title;
						this.public_content = this.imgDesc(res.data.descript);
					}
				})
			},
			closeBox(){
				this.showBox = false
			},
			openBox(type){
				this.read_type = type;
				if(type == 1){
					this.show_title = this.service_title;
					this.show_content = this.service_content;
				}
				if(type == 2){
					this.show_title = this.public_title;
					this.show_content = this.public_content;
				}
				
				this.showBox = true;
			},
			hasRead(){
				console.log(this.read_type);
				if(this.read_type == 1){
					this.read_service_finish = true;
				}
				if(this.read_type == 2){
					this.read_public_finish = true;
				}
				if(this.read_service_finish && this.read_public_finish){
					this.loginModel.checked = true;
				}
				
				this.showBox = false;
			},
			imgDesc(html){
				if(html == ''){
					return html;
				}
			  // return str.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin-top:10px"');
				html = html.replace(/text-align: justify;/gi,'');
				html = html.replace(/style=""/gi,'');
				html = html.replace(/<p>/gi,"<p style='width:100%'>");
				// html = html.replace(/<\/p>/gi,'');
				let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
				    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
				    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
				    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
				    return match;
				  });
				  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
				    match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
				    return match;
				  });
				  // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
				  newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin-top:0;margin-bottom:7px;"');
				  return newContent;
			},
			showPwd(type){
				if(type == 'close'){
					this.show_pwd = false;
					this.pwd_put = true;
				}else{
					this.show_pwd = true;
					this.pwd_put = false;
				}
			}
		}
	}

</script>

<style scoped>
	.container {
		width: 750rpx;
		height: 100vh;
		position: relative;
		background: #FFFFFF;
	}
.top_tit{
	font-size: 60rpx;
	color: #fff;
	text-align: center;
	font-weight: 600;
	margin:40rpx 0rpx;
}
.top_logo{
	padding: 20rpx;
	width: 100%;
	display: flex;
	justify-content: start;
	background-color: #000;
}
.top_logo .logo{
	width: 200rpx;
}
	.head {
		width: 100%;
		padding-left: 50rpx;
		margin-top: 80rpx;
	}

	.head-title_1 {
		font-size: 42rpx;
		font-family: PingFangSC;
		font-weight: 500;
		color: #333333;
	}

	.head-title_2 {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #999999;
		margin-top: 30rpx;
	}

	::v-deep .u-form {
		margin-top: 100rpx;
	}

	.form-item {
		width: 640rpx;
		height: 100rpx;
	}

	::v-deep .u-form-item__body {
		padding: 0 !important;
	}

	::v-deep input {
		padding-left: 30rpx;
	}

	.get-code {
		height: 100%;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #6565E7;
	}

	::v-deep .u-checkbox-group {
		width: 10%;
	}

	.agreement {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #999999;
	}

	.agreement text {
		color: #6565E7;
	}

	.login-button {
		width: 100%;
		height: 92rpx;
		background: #2e3033;
		font-size: 34rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		margin-top: 100rpx;
		border-radius: 10rpx;
	}
.login-button view{
	width: 100%;
	height: 92rpx;
	line-height: 92rpx;
	text-align: center;
}
	.password-login {
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #999999;
		margin-top: 28rpx;
		text-align: center;
	}

	.other-login {
		position: absolute;
		bottom: calc(30rpx + env(safe-area-inset-bottom));
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #999999;
		width: 100%;
		left: 0;
		right: 0;
		margin: auto;
	}

	.other-login>view:last-child {
		margin-top: 30rpx;
	}

	.login-image {
		margin: 0 5rpx;
	}

	.line {
		height: 100%;
		width: 2rpx;
		background: #E1DFDF;
		position: absolute;
	}

	.login-botton {
		background-color: none;
	}

	.icon-img {
		width: 300rpx;
		height: 300rpx;
	}

	.weixin {
		padding: 50rpx;

	}

	.head-icon {
		left: 0;
		right: 0;
		margin: auto;
		margin-top: 30%;
		margin-bottom: 20%;
	}

	.rules {
		color: #999;
		font-size: 24rpx;
		text-align: center;
		display: flex;
	}

	.wlogin {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}

	.login-botton {
		margin-bottom: 50rpx;
		background: #78bb7b !important;
		color: #fff !important;
		margin-top: 10%;

	}
	.login-botton2 {
		margin-bottom: 50rpx;
		background: #4caf50 !important;
		color: #fff !important;
		margin-top: 10%;

	}
	.others-login {
		font-size: 34rpx;
		width: 590rpx;
		height: 92rpx;
		background: #fff;
		text-align: center;
		line-height: 92rpx;
		border-radius: 5px;
	}
.scrollable-area {
	padding: 40rpx 30rpx;
    max-height: 77vh; /* 充满父容器的高度 */  
   -webkit-overflow-scrolling: touch;  
}
.agren_btn{
	margin-top: 24rpx;
	width: 100%;
	line-height: 32rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #000;
	font-size: 30rpx;
}
.xuanzhong{
	width: 54rpx;
	height: 54rpx;
	margin-right: 10rpx;
}
</style>

